package com.kingtone.rongji;

import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import com.kingtone.rongji.biz.CommonMessage;
import com.kingtone.rongji.network.UserRequest;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.ToastManager;

public class LoginActivity extends BaseActivity implements
		PlatformActionListener {

	private static final String TAG = "LoginActivity";

	private static final int REGISTER_FLOW = 0;
	
	private Handler handler;

	private Button mRegisterBtn;

	private Button mLoginBtn;

	private EditText mUserName;

	private EditText mPassword;

	private TextView mFindPwd;
	
	private boolean isProductDetail;
	
	private String productId;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		this.setContentView(R.layout.activity_login);
		setupView();
		handler = new MyHandler();
		isProductDetail = this.getIntent().getBooleanExtra("fromProductDetail", false);
		productId = this.getIntent().getStringExtra("productId");
	}

	private void setupView() {

		initTitleView(getString(R.string.title_login));

		mUserName = (EditText) this.findViewById(R.id.id_et_username);
		mPassword = (EditText) this.findViewById(R.id.id_et_password);

		mLoginBtn = (Button) this.findViewById(R.id.id_bt_login);
		mLoginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String account = mUserName.getText().toString();
				String password = mPassword.getText().toString();
				if (account.equals("")) {
					ToastManager.show(
							mContext,
							getResources().getString(
									R.string.login_username_empty_label));
					return;
				} else if (password.equals("")) {
					ToastManager.show(
							mContext,
							getResources().getString(
									R.string.login_password_empty_label));
					return;
				}
				UserRequest loginRequest = new UserRequest();
				loginRequest.login(account, password, LoginActivity.this);
			}
		});

		mRegisterBtn = (Button) this.findViewById(R.id.id_bt_reg);
		mRegisterBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivity(intent);
			}
		});

		mFindPwd = (TextView) this.findViewById(R.id.id_find_pwd);
		mFindPwd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this,
						PasswordStep1Activity.class);
				startActivity(intent);
			}
		});

		ImageView weixin = (ImageView) this.findViewById(R.id.id_weinxin_login);
		weixin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Platform wechat = ShareSDK.getPlatform(mContext, Wechat.NAME);
				wechat.setPlatformActionListener(LoginActivity.this);
				authorize(wechat);
			}
		});

		ImageView qq = (ImageView) this.findViewById(R.id.id_qq_login);
		qq.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Platform qq = ShareSDK.getPlatform(mContext, QQ.NAME);
				qq.setPlatformActionListener(LoginActivity.this);
				authorize(qq);
			}
		});

		ImageView weibo = (ImageView) this.findViewById(R.id.id_weibo_login);
		weibo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Platform weibo = ShareSDK.getPlatform(mContext, SinaWeibo.NAME);
				weibo.setPlatformActionListener(LoginActivity.this);
				authorize(weibo);
			}
		});
	}

	private void authorize(Platform plat) {
		if (plat == null) {
			return;
		}
		if (plat.isValid()) {
			String userId = plat.getDb().getUserId();
			if (userId != null) {
				userId = plat.getName() + "_" + userId;
				UserRequest userRequest = new UserRequest();
				userRequest.login(convertEmail(plat.getName(), userId), userId, this);
				return;
			}
		}
		plat.setPlatformActionListener(this);
		plat.SSOSetting(true);
		plat.showUser(null);
	}

	public void onComplete(Platform platform, int action,
			HashMap<String, Object> res) {
		if (action == Platform.ACTION_USER_INFOR) {
			Message msg = new Message();
			msg.what = REGISTER_FLOW;
			msg.obj = new Object[] {platform.getName(), platform.getDb()};
			handler.sendMessage(msg);
		}
	}

	public void onError(Platform platform, int action, Throwable t) {
		t.printStackTrace();
	}

	public void onCancel(Platform platform, int action) {
	}

	class MyHandler extends Handler {
		public MyHandler() {
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case REGISTER_FLOW:
					Object[] objs = (Object[]) msg.obj;
					PlatformDb db = (PlatformDb) objs[1];
					String platName = (String) objs[0];
					String realName = db.getUserName();
					String userIcon = db.getUserIcon();
					String gender = db.getUserGender();
					String userId  = platName + "_" + db.getUserId();
					UserRequest userRequest = new UserRequest();
					userRequest.loginByThirdPart(userId, convertEmail(platName, userId), realName, userIcon,
							gender.equalsIgnoreCase("m") ? 0 : 1,
							LoginActivity.this);
					break;
				default:
					break;
			}
		}
	}

	/**
	 * ���ؼ�
	 */
	public void onBackPressed() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	@Override
	public void onBussinessSuccess(Object obj) {
		super.onBussinessSuccess(obj);
		if (obj instanceof CommonMessage) {
			SharedPreferencesUtil shared = SharedPreferencesUtil
					.getInstance(mContext);
			shared.putBoolean(AppContasts.IS_LOGINED_KEY, true);
			CommonMessage common = (CommonMessage) obj;
			shared.putString(AppContasts.USERID_KEY, common.getTag());
			if(isProductDetail)
			{
				Intent intent = new Intent(LoginActivity.this, ProductDetailActivity.class);
				intent.putExtra("productId", productId);
				startActivity(intent);
				finish();
			}
			else
			{
				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
			}
		}
	}

	@Override
	public void onBussinessError(String errorMessage) {
		// TODO Auto-generated method stub
		super.onBussinessError(errorMessage);
	}
	
	public String convertEmail(String platName, String userId)
	{
		String endStr = "@rongji365.com";
		if("SinaWeiBo".equalsIgnoreCase(platName))
		{
			endStr = "@sina.com";
		}
		else if("qq".equalsIgnoreCase(platName))
		{
			endStr = "@qq.com";
		}
		else if("WeiXin".equalsIgnoreCase(platName))
		{
			endStr = "@weixin.com";
		}
		return userId.concat(endStr);
	}
}
